/**
 * User: 夏汛
 * Date: 12-9-28
 * Time: 上午11:03
 */
Ext.extend(app.module,{
    currentFormValues: {},
    rankRecord:Ext.data.Record.create([
        {name:'id',type:'string'},
        {name:'name',type:'string'},
        {name:'deptname',type:'string'},
        {name:'titlename',type:'string'}
    ]),
    init: function(){
        mainPanel = this;
        this.projectforuserDs = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({url:'crossproject/listProjectForUser.do'}),
            reader: new Ext.data.JsonReader({
                totalProperty: 'total',
                root: 'rows',
                idProperty: 'id'
            },[
                {name:'id'},
                {name:'name'},
                {name:'description'},
                {name:'projecttype'},
                {name:'state'},
                {name:'reporttime'},
                {name:'approvaltime'},
                {name:'planendtime'},
                {name:'endtime'},
                {name:'tasktime'},
                {name:'middletime'},
                {name:'finishtime'},
                {name:'filepath'},
                {name:'taskpath'},
                {name:'remain'},
                {name:'filename'},
                {name:'projectTypeName'},
                {name:'iscross'},
                {name:'approvedept'},
                {name:'rank'},
                {name:'money'},
                {name:'shoolmoney'},
                {name:'remarks'},
                {name:'deptname'}
            ])
        });
        this.loader = new Ext.tree.JsonPluginTreeLoader({dataUrl:'dept/getDeptTree.do'});
        this.rankDs = new Ext.data.Store({
            proxy: new Ext.data.MemoryProxy({'total':1,'rows':[]}),
            reader: new Ext.data.JsonReader({
                totalProperty: 'total',
                root: 'rows',
                idProperty: 'id'
            },[
                {name:'id'},
                {name:'name'},
                {name:'deptname'},
                {name:'titlename'}
            ])
        });

        this.fileDs = new Ext.data.Store({
            proxy: new Ext.data.MemoryProxy({'total':1,'rows':[]}),
            reader: new Ext.data.JsonReader({
                totalProperty: 'total',
                root: 'rows',
                idProperty: 'id'
            },[
                {name:'id'},
                {name:'filename'}
            ])
        });

        this.body = new Ext.grid.GridPanel({
            store: this.projectforuserDs,
            region: 'center',
            loadMask: true,
            viewConfig:{
                forceFit:true
            },
            columns: [
                new Ext.grid.RowNumberer(),
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'name',
                    header: '点击课题名称查看',
                    renderer:function(value, cellmeta, record, rowIndex, columnIndex, store){
                        return '<a href="javascript:void(0)" onclick="mainPanel.getFileViewDlg('+
                            record.data["id"]+')">'+value+'</a>';
                    }
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'approvedept',
                    header: '来源部门'
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'projectTypeName',
                    header: '课题类型'
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'money',
                    width: 50,
                    header: '经费'
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'rank',
                    width: 30,
                    header: '排名'
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'state',
                    header: '状态',
                    width: 50,
                    renderer:function(value, cellmeta, record, rowIndex, columnIndex, store){
                        if(value==0){
                            return "审核中";
                        } else if (value==8 ){
                            return "立项";
                        } else {
                            return "";
                        }
                    }
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'description',
                    header: '备注'
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'id',
                    header: '操作',
                    width: 120,
                    renderer:function(value, cellmeta, record, rowIndex, columnIndex, store){
                        return ' <a href="javascript:void(0)" onclick="mainPanel.getUploadDlg('+value+')">上传课题材料</a>';
                    }
                }
            ],
            tbar: {
                xtype: 'toolbar',
                items: [
                    {
                        text: '上报横向课题',
                        iconCls : 'add',
                        scope: this,
                        handler: this.add
                    }
                ]
            },
            bbar: {
                xtype: 'paging',
                pageSize: 15,
                displayInfo: true,
                store: this.projectforuserDs
            }
        });
        this.main.add(this.body);
        this.main.doLayout();
        this.projectforuserDs.load({
            params: {start:0, limit:15 }
        });
    },
    getProjectforuserDialog: function(){
        this.form = this.getForm();
        this.rankGrid = this.getRankDrid();
        var inSchoolForm = this.getInSchoolForm();
        var dlg = new Ext.Window({
            height: 440,
            width: 750,
            layout: 'fit',
            border: false,
            title: '上报横向课题',
            buttonAlign:'center',
            modal: true,
            plain: true,
            layout: 'border',
            resizable: false,
            items: [
                {
                    xtype: 'panel',
                    layout: 'column',
                    region: 'center',
                    items: [
                        {
                            columnWidth:.5,
                            layout: 'form',
                            xtype: 'fieldset',
                            title: '课题信息',
                            defaults: {anchor: '95%'},
                            style: 'margin:5px;padding:5px',
                            items:[this.form]
                        },
                        {
                            columnWidth:.5,
                            layout: 'form',
                            xtype: 'fieldset',
                            title: '添加参与人员',
                            style: 'margin:5px;padding:5px',
                            defaults: {anchor: '95%'},
                            items:[inSchoolForm]
                        }
                    ]
                },
                this.rankGrid
            ],
            listeners: {
                scope: this,
                render: function(fp){
                    this.form.getForm().waitMsgTarget = fp.getEl();
                },
                show: function(){
                    var f = this.form.getForm();
                    f.setValues(this.currentFormValues);
                    f.clearInvalid();
                }
            },
            buttons: [{
                text: '保存',
                scope: this,
                handler: function() {
                    this.submit();
                }
            }]
        });
        return dlg;
    },
    getRankDrid: function() {
        mainPanel = this;
        var grid = new Ext.grid.GridPanel({
            height: 230,
            store: this.rankDs,
            region: 'north',
            viewConfig:{
                forceFit:true
            },
            columns: [
                new Ext.grid.RowNumberer(),
                {
                    xtype: 'gridcolumn',
                    dataIndex: 'id',
                    hidden: true
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'name',
                    header: '姓名'
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'deptname',
                    header: '部门'
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'titlename',
                    header: '职称'
                },
                {
                    xtype: 'actioncolumn',
                    width: 50,
                    items: [
                        {
                            icon   : '../images/icons/up.png',
                            tooltip: '上移',
                            handler: function(grid, rowIndex, colIndex) {
                                //第一行和第二行不允许上移
                                if(rowIndex==0 || rowIndex==1){
                                    return;
                                } else {
                                    var record = mainPanel.rankDs.getAt(rowIndex);
                                    mainPanel.rankDs.removeAt(rowIndex);
                                    mainPanel.rankDs.insert(rowIndex-1,record);
                                }
                            }
                        },
                        {
                            icon   : '../images/icons/down.png',
                            tooltip: '下移',
                            handler: function(grid, rowIndex, colIndex) {
                                //第一行和最后一行不允许下移
                                if(rowIndex==0 || rowIndex==mainPanel.rankDs.getCount()-1){
                                    return;
                                } else {
                                    var record = mainPanel.rankDs.getAt(rowIndex);
                                    mainPanel.rankDs.removeAt(rowIndex);
                                    mainPanel.rankDs.insert(rowIndex+1,record);
                                }
                            }
                        },
                        {
                            icon   : '../images/icons/del.png',
                            tooltip: '删除',
                            handler: function(grid, rowIndex, colIndex) {
                                //第一行不允许删除
                                if(rowIndex==0){
                                    return;
                                } else {
                                    mainPanel.rankDs.removeAt(rowIndex);
                                    grid.view.refresh();
                                }
                            }
                        }
                    ]
                }
            ]
        });
        return grid;
    },
    getInSchoolForm: function(){
        mainPanel = this;
        var userStore = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({url:'user/listUserByDeptid.do'}),
            reader: new Ext.data.JsonReader({
                totalProperty: 'total',
                root: 'rows',
                idProperty: 'id'
            },[
                {name:'id'},
                {name:'username'}
            ])
        });
        var comboUser = new Ext.form.ComboBox({
            store: userStore,
            editable: false,
            emptyText: '请选择人员...',
            mode: 'local',
            hiddenName : 'userid',
            typeAhead : true,
            triggerAction : 'all',
            displayField: 'username',
            valueField: 'id',
            fieldLabel: '人员'
        });
        selectDeptTree = new Ext.tree.TreePanel( {
            loader: this.loader,
            root : {
                id: 0,
                text: '根节点',
                expanded: true
            },
            autoScroll : false,
            rootVisible : false,// 根节点是否可见
            animate : false,    // 展开,收缩动画
            useArrows : false,  // 是否使用箭头样式
            lines:false,        // 去掉树的线
            border : false
        });
        // 监听下拉树的节点单击事件
        selectDeptTree.on('click', function(node) {
            if(node.leaf){
                mainPanel.comboxWithDeptTree.setValue(node.text);
                userStore.load({params:{deptid:node.id}});
                mainPanel.comboxWithDeptTree.collapse();
            } else {
                Ext.Msg.alert("提示","不能选择有下级部门的节点！");
            }
        });
        this.comboxWithDeptTree = new Ext.form.ComboBox({
            fieldLabel: '所属部门',
            store : new Ext.data.SimpleStore( {
                fields : [],
                data : [[]]
            }),
            autoScroll : true,
            value : '',
            emptyText : '请选择部门...',
            mode : 'local',
            editable: false,
            triggerAction : 'all',
            maxHeight : 390,
            // 下拉框的显示模板,deptTreeDiv作为显示下拉树的容器
            tpl : "<tpl for='.'><div style='height:390px'><div id='projectforuserSelectDeptTreeDiv'></div></div></tpl>",
            onSelect : Ext.emptyFn,
            onViewClick : Ext.emptyFn,
            assertValue : Ext.emptyFn
        });
        // 监听下拉框的下拉展开事件
        this.comboxWithDeptTree.on('expand', function() {
            // 将树挂到treeDiv容器
            selectDeptTree.render('projectforuserSelectDeptTreeDiv');
        });
        var inForm = new Ext.form.FormPanel({
            region: 'center',
            defaultType: 'textfield',
            bodyStyle: 'padding:5px',
            buttonAlign: 'center',
            url:'user/saveOutSchoolUser.do',
            defaults: {anchor: '95%'},
            layout:'form',
            labelWidth: 70,
            submitEmptyText: false,     //禁止提交emptyText
            items: [
                this.comboxWithDeptTree,
                comboUser
            ],
            buttons: [{
                text: '增加',
                scope: this,
                handler: function() {
                    var userid = comboUser.getValue();
                    if(!(userid=='' || userid==undefined)){
                        //遍历store方法：mainPanel.rankDs.getAt(i).data.id
                        for (var i = 0; i < mainPanel.rankDs.data.length; i++) {
                            if(userid==mainPanel.rankDs.getAt(i).data.id){
                                Ext.Msg.alert('提示','已经增加过了');
                                inForm.getForm().reset();
                                return;
                            }
                        }
                        Ext.Ajax.request({
                            method:'post',
                            url:'user/selectById.do',
                            params:{
                                id: userid
                            },
                            scope: this,
                            success: function(resp, opts) {
                                var result = Ext.util.JSON.decode(resp.responseText);
                                var user = result.user;
                                var p = new mainPanel.rankRecord({
                                    id: comboUser.getValue(),
                                    name: user.username,
                                    deptname: user.deptname,
                                    titlename: user.titlename
                                });
                                mainPanel.rankDs.add(p);
                                inForm.getForm().reset();
                            }
                        });
                    }
                }
            }]
        });
        return inForm;
    },
    getForm: function(){
        mainPanel = this;
        var form = new Ext.form.FormPanel({
            region: 'center',
            defaultType: 'textfield',
            bodyStyle: 'padding:5px',
            buttonAlign: 'center',
            url:'crossproject/save.do',
            labelWidth: 70,
            defaults: {anchor: '95%'},
            layout:'form',
            submitEmptyText: false,     //禁止提交emptyText
            items: [
                {
                    fieldLabel: '课题名称',
                    xtype: 'textfield',
                    allowBlank: false,
                    name: 'name'
                },
                {
                    fieldLabel: '联合部门',
                    emptyText: '请填写联合部门',
                    xtype: 'textfield',
                    allowBlank: false,
                    name: 'approvedept'
                },
                {
                    xtype: 'numberfield',
                    name: 'money',
                    allowDecimals:false,
                    emptyText: '请填写数字',
                    fieldLabel: '经费'
                }
            ]
        });
        return form;
    },
    add: function() {
        this.dlg = this.getProjectforuserDialog();
        var p = new this.rankRecord({
            id: globeUserId,
            name: globeUserName,
            deptname: globeDeptName,
            titlename: globeTitlename
        });
        this.rankDs.clearData();
        this.rankDs.add(p);
        this.dlg.setTitle("上报横向课题");
        this.dlg.show();
    },
    submit: function(){
        if (this.form.getForm().isValid()) {
            var ids = [];
            for(i=0;i<this.rankDs.getCount();i++){
                ids.push(this.rankDs.getAt(i).data.id);
            }
            this.form.getForm().submit({
                waitTitle: '保存数据',
                waitMsg: '正在保存……',
                scope: this,
                method: 'post',
                params: {
                    ids: ids.toString()
                },
                submitEmptyText: false,     //禁止提交emptyText
                success: function(form, action) {
                    var info = action.result.info;
                    if (action.result.success) {
                        this.projectforuserDs.reload();
                        this.form.getForm().reset();
                        this.dlg.close();
                    }
                    Ext.Msg.alert('信息', info);
                },
                failure: function(form, action) {
                    var info = action.result.info;
                    Ext.Msg.alert('提示', info);
                }
            });
        }
    },
    getUploadDlg:function(projectId){
        var win = new Ext.Window({
            width : 650,
            title : '上传课题材料',
            height : 300,
            layout : 'fit',
            items : [
                {
                    xtype:'uploadPanel',
                    border : false,
                    fileSize : 1024*550,//限制文件大小
                    uploadUrl : 'file/upload.do',
                    flashUrl : 'swfupload/swfupload.swf',
                    filePostName : 'file', //后台接收参数
                    fileTypes : '*.doc;*.docx;*.pdf;*.zip;*.rar;*.jpg;*.gif',//可上传文件类型
                    postParams : {projectId:projectId} //上传文件存放目录
                }
            ]
        }).show();
    }
});